#!/bin/bash

set -eu -o pipefail

helpexit() {
  echo "$0 install|check|update <url>"
  exit 1
}

test -n "${1:-}" || helpexit
action=$1
appimage=Paimon_Launcher.AppImage
bin_path="$HOME/.local/bin/"
bin_appimage="$bin_path$appimage"
launcher_path="$HOME/.local/share/paimon-launcher/"
launcher_bin=${launcher_path}bin/

install() {
  check
  echo "Installing v$version"
  update "$link"
  echo
  echo "Installation to $bin_appimage finished"
  echo
  echo "Command to start launcher:"
  echo "  $appimage"
}

check() {
  url='https://notabug.org/loentar/paimon-launcher/releases'

  temp=`mktemp`
  trap "rm -f '$temp'" EXIT

  aria2c --allow-overwrite --dir `dirname "$temp"` -o `basename "$temp"` "$url" >&2
  whole_content=$(<$temp)
  content=`sed '/<ul id="release-list"/,/span class="dot"/!d;/href=/!d' <<< "$whole_content"`

  version=`sed '/tag icon/!d;s/<[^>]*>//g;s/[ \t]*//g' <<< "$content"`
  link=`sed '/google/!d;s/.*href="//g;s/".*//g' <<< "$content"`
  if [ -e "$launcher_bin$appimage" ]; then
    mode=update
  else
    mode=download
  fi
  echo "PLVERSION $mode $version $link"
}

update() {
  appimage_url=${1:-}
  if [ -z "$appimage_url" ]; then
    helpexit
  fi

  mkdir -p "$launcher_bin"
  mkdir -p "$bin_path"

  launcher=${launcher_path}bin/$appimage

  # https://drive.google.com/file/d/1GC-PFibSdo8Mwx2xG50gcfia3wSClN87/view?usp=sharing
  #   vvv
  # https://drive.google.com/uc?id=1GC-PFibSdo8Mwx2xG50gcfia3wSClN87&export=download
  download_link=`sed 's/file\/d\//uc\?id=/;s/\/view.*/\&export=download/' <<< "$appimage_url"`

  echo "$download_link"
  aria2c --allow-overwrite --dir "$launcher_bin" -o "$appimage.new" "$download_link"
  if [ -f "$launcher" ]; then
    mv -f "$launcher" "$launcher.bak"
  fi
  mv -f "$launcher.new" "$launcher"
  chmod +x "$launcher"
  ln -nsf "$launcher" "$bin_appimage"
}

restart() {
  ($launcher >/dev/null 2>&1) &
  disown
}

case "$action" in
  install)
    install
    ;;

  check)
    check
    ;;

  update)
    update "$2"
    restart
    ;;

  *)
    helpexit
    ;;
esac
